package com.angel.application.event.handler;

import com.angel.domain.angelhelp.repositories.AngelHelpRepository;
import com.angel.domain.angelhelp.valueobjects.AngelHelpId;
import com.angel.domain.angelmission.aggregates.AngelMission;
import com.angel.domain.angelmission.domainservice.AngelMissionDomainService;
import com.angel.domain.angelmission.repositories.AngelMissionRepository;
import com.angel.domain.angeluser.event.AngelUserRegisterEvent;
import com.angel.domain.angeluser.valueobjects.AngelUserId;
import com.angel.infrastructure.db.mapper.HelpInfoMapper;
import com.angel.infrastructure.db.po.HelpInfoPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

/*
 * 更新关注微信公众号： 为了offer
 * @author parkin
 * @description
 * @date 2021/11/14
 */
@Slf4j
@Component
public class UserRegisterEventHandler {

    private final AngelHelpRepository angelHelpRepository;
    private final AngelMissionRepository angelMissionRepository;
    private final HelpInfoMapper helpInfoMapper;

    public UserRegisterEventHandler(AngelHelpRepository angelHelpRepository,
                                    AngelMissionRepository angelMissionRepository,
                                    HelpInfoMapper helpInfoMapper) {

        this.angelHelpRepository = angelHelpRepository;
        this.angelMissionRepository = angelMissionRepository;
        this.helpInfoMapper = helpInfoMapper;
    }

    /**
     * 新用户初始化任务列表
     */
    @EventListener
    public void initAngelMission(AngelUserRegisterEvent angelUserRegisterEvent) {
        AngelUserId angelUserId = angelUserRegisterEvent.getAngelUserRegisterEventData().getAngelUserId();
        /**
         * 查询固定数量还未回答或者回答很少的任务加入任务列表
         */
        List<HelpInfoPO> angelMissionsOfWait = helpInfoMapper.getHelpInfosOrderByVoiceNumberAndDesc(3);

        angelMissionsOfWait.stream().forEach(angelHelp -> distributeMissionOfVoice(angelUserId,AngelHelpId.toAngelHelpId(angelHelp.getHelpId())));
    }

    private void distributeMissionOfVoice(AngelUserId angelUserId,AngelHelpId angelHelpId) {
        AngelMission angelMission = AngelMissionDomainService.distributeMission("去发出声音", angelUserId, angelHelpId);
        angelMissionRepository.save(angelMission);
    }
}
